<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <!-- 标题 -->
          <span>试题{{$route.query.id ? '修改' : '录入'}}</span>
        </div>
        <div class="text item">
          <!-- 表单 -->
          <el-form
            ref="qstForm"
            :model="qstForm"
            label-width="85px"
            class="qstForm"
            :rules="rules"
          >
            <!-- 学科 -->
            <el-form-item label="学科:" prop="subjectID">
              <el-select
                v-model="qstForm.subjectID"
                placeholder="请选择"
                style="width: 400px"
                @change="subjectSelect"
              >
                <el-option
                  v-for="item in subList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <!-- 目录 -->
            <el-form-item label="目录:" prop="catalogID">
              <el-select
                v-model="qstForm.catalogID"
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option
                  v-for="item in directorysList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <!-- 企业 -->
            <el-form-item label="企业:" prop="enterpriseID">
              <el-select
                v-model.number="qstForm.enterpriseID"
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option
                  v-for="item in companysList"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <!-- 城市 -->
            <el-form-item label="城市:" prop="city">
              <QuestionCascader ref="cityCascader" :city.sync="qstForm.city" :province.sync="qstForm.province" style="width:400px;"></QuestionCascader>
            </el-form-item>
            <!-- 方向 -->
            <el-form-item label="方向:" prop="direction">
              <el-select
                v-model="qstForm.direction"
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option
                  v-for="item in direction"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 题型 -->
            <el-form-item label="题型:" prop="questionType">
              <el-radio-group v-model="qstForm.questionType">
                <el-radio
                  v-for="item in questionType"
                  :key="item.value"
                  :label="(item.value).toString()"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 难度 -->
            <el-form-item label="难度:" prop="difficulty">
              <el-radio-group v-model="qstForm.difficulty">
                <el-radio
                  v-for="item in difficulty"
                  :key="item.value"
                  :label="(item.value).toString()"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 题干 -->
            <el-form-item label="题干:" prop="question">
              <quill-editor
                class="editor"
                style="margin-bottom:40px; height: 200px"
                v-model.trim="qstForm.question"
                :options="editorOption"
                @blur="questionBlur"
              >
              </quill-editor>
            </el-form-item>
            <!-- 选项 -->
            <el-form-item v-if="qstForm.questionType !== '3'" label="选项:" style="margin-top: 30px" prop="options">
            <!-- 单选组 -->
              <el-radio-group v-if="qstForm.questionType === '1'" v-model="isRight" @change="radioChange">
                <el-row
                  type="flex"
                  justify="start"
                  align="middle"
                  style="margin-bottom: 20px"
                  v-for="(item,index) in qstForm.options" :key="item.code"
                >
                  <el-col :span="5">
                    <el-radio :label="item.code">{{item.code}}:</el-radio>
                  </el-col>
                  <el-col :span="24">
                    <el-input
                      style="width: 240px; margin-right: 5px"
                      v-model="item.title"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    <!-- 上传图片 -->
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                      @click.native="num = index"
                    >
                      <img v-if="item.img" :src="item.img" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                      <div v-if="item.img" @click.stop="removeImg(index)" class="removeImg"><i class="el-icon-close"></i></div>
                  </el-col>
                </el-row>
              </el-radio-group>
            <!-- 多选组 -->
              <el-checkbox-group v-else v-model="checkList" @change="checkboxChange">
                <el-row
                  type="flex"
                  justify="start"
                  v-for="(item,index) in qstForm.options" :key="item.code"
                >
                    <el-checkbox :label="item.code" style="margin-top:14px;">{{item.code}}:</el-checkbox>
                    <el-input
                      style="width: 240px; margin:14px 5px 0"
                      v-model="item.title"
                    ></el-input>
                    <!-- 上传图片 -->
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                      @click.native="num = index"
                    >
                      <img v-if="item.img" :src="item.img" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-row>
              </el-checkbox-group>
            <!-- 增加选项与答案按钮 -->
              <el-row>
                <el-button @click="addOptions" type="danger" size="small" :disabled="qstForm.questionType === '1'"><span>+增加选项与答案</span></el-button>
              </el-row>
            </el-form-item>
            <!-- 解析视频 -->
            <el-form-item
              label="解析视频:"
              style="margin-top:30px"
              prop="videoURL"
            >
              <el-input
                v-model="qstForm.videoURL"
                style="width: 400px"
              ></el-input>
            </el-form-item>
            <!-- 答题解析 -->
            <el-form-item label="答题解析:" prop="answer">
              <quill-editor
                class="editor"
                style="margin-bottom:42px; height:200px"
                v-model.trim="qstForm.answer"
                :options="editorOption"
                @blur="answerBlur"
              >
              </quill-editor>
            </el-form-item>
            <!-- 题目备注 -->
            <el-form-item label="题目备注:" prop="remarks">
              <el-input
                rows="4"
                type="textarea"
                v-model="qstForm.remarks"
                style="width: 400px"
              ></el-input>
            </el-form-item>
            <!-- 试题标签 -->
            <el-form-item label="试题标签:" prop="tags">
              <el-select
                v-model="qstForm.tags"
                placeholder="请选择试题标签"
                style="width: 400px"
                multiple
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 提交按钮 -->
            <el-form-item>
              <el-button type="primary" @click="btnSubmit">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as subjectsList } from '@/api/hmmm/subjects'
import { simple as directorysList } from '@/api/hmmm/directorys'
import { simple as tagsList } from '@/api/hmmm/tags'
import { list as companysList } from '@/api/hmmm/companys'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'

export default {
  data () {
    return {
      isRight: null,
      checkList: [],
      num: null,
      questionType,
      difficulty,
      direction,
      content: null,
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link', 'image', 'video']
          ]
        },
        placeholder: '',
        theme: 'snow'
      },
      qstForm: {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        city: '',
        province: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      rules: {
        subjectID: [{ required: true, message: '学科必选', trigger: 'change' }],
        catalogID: [{ required: true, message: '目录必选', trigger: 'change' }],
        enterpriseID: [
          { required: true, message: '企业必选', trigger: 'change' }
        ],
        direction: [{ required: true, message: '方向必选', trigger: 'change' }],
        city: [{ required: true, message: '城市必选', trigger: 'change' }],
        questionType: [
          { required: true, message: '题型必选', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '难度必选', trigger: 'change' }
        ],
        question: [{ required: true, message: '题干必填' }],
        answer: [{ required: true, message: '答题解析必填' }]
      },
      subList: [],
      directorysList: [],
      companysList: [],
      tagsList: []
    }
  },
  async created () {
    const { data } = await subjectsList()
    this.subList = data
    const {
      data: { items }
    } = await companysList({ pagesize: 10000 })
    this.companysList = items
    // 判断是否是编辑
    if (this.$route.query.id) {
      await this.getQuestiondetail(this.$route.query.id)
    }
    document.documentElement.scrollTop = 0
  },
  methods: {
    // 获取基础题库详情
    async getQuestiondetail (id) {
      const { data } = await detail({ id })
      this.qstForm = data
      const { province, city } = data
      this.$refs.cityCascader.updateCity(province, city)
      this.qstForm.tags = [this.qstForm.tags]
      const res = []
      data.options.forEach(item => {
        if (item.isRight === 1) { res.push(item.code) }
      })
      if (res.length === 1) {
        this.isRight = res[0]
      } else {
        this.checkList = res
      }
    },
    // 学科选择
    async subjectSelect () {
      this.qstForm.catalogID = null
      this.qstForm.tags = ''
      const { data } = await directorysList({
        subjectID: this.qstForm.subjectID
      })
      this.directorysList = data
      const { data: tags } = await tagsList({
        subjectID: this.qstForm.subjectID
      })
      this.tagsList = tags
    },
    // 图片上传成功的回调
    handleAvatarSuccess (res, file) {
      this.qstForm.options[this.num].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 移除图片
    removeImg (index) {
      this.qstForm.options[index].img = ''
    },
    // 增加选项按钮
    addOptions () {
      const arr = this.qstForm.options.map(item => item.code)
      const code = String.fromCharCode(arr.length + 65)
      this.qstForm.options.push({
        isRight: false, code, title: '', img: ''
      })
    },
    // 选项单选
    radioChange (code) {
      this.qstForm.options.forEach(item => {
        item.isRight = false
      })
      const res = this.qstForm.options.find(item => item.code === code)
      res.isRight = true
    },
    // 选项多选
    checkboxChange () {
      this.qstForm.options.forEach(item => {
        item.isRight = false
      })
      this.checkList.forEach(code => {
        const res = this.qstForm.options.find(item => item.code === code)
        res.isRight = true
      })
    },
    // 题干失去焦点校验
    questionBlur () {
      this.$refs.qstForm.validateField('question')
    },
    // 答题解析失去焦点校验
    answerBlur () {
      this.$refs.qstForm.validateField('answer')
    },
    // 提交按钮
    async btnSubmit () {
      try {
        // 表单校验
        await this.$refs.qstForm.validate()
        // 调接口
        if (this.qstForm.id) {
          // 编辑
          await update(this.qstForm)
        } else {
          // 新增
          await add(this.qstForm)
        }
        // 页面跳转到基础题库
        this.$router.push('/questions/list')
        // 提示用户
        this.$message.success(this.qstForm.id ? '修改试题成功!' : '新增试题成功!')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style >
.ql-toolbar.ql-snow{
  padding: 0 0 0 8px !important;
}
.qstForm {
  padding-left: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 16px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 10px;
  text-align: right;
}
.removeImg{
  width: 18px;
  height: 18px;
  border: 2px solid gray;
  border-radius: 50%;
  position: absolute;
  right: -13px;
  top: -7px;
  color: gray;
  line-height: 18px;
  text-align: center;
  i {
    font-size: 15px;
    font-weight: 700;
  }
}
</style>
